<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">

      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-form label-width="70px" size="small">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startBusDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endBusDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
              </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="部门">
                <!-- <TreeSelect
                  v-model="query.deptIds"
                  :options="depts"
                  placeholder="选择部门"
                  style="width:  100%"
                  :normalizer="normalizer"
                /> -->
                <zSelect :value.sync="query.deptIds" url="api/dropDown/childSysDeptList" style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="人员">
                <zSelect :value.sync="query.userIds" url="api/dropDown/sysUserList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <rrOperation :crud="crud"/>
          </el-row>
        </el-form>
      </div>
      <crudOperation :permission="permission">
        <el-button type="primary" size="mini" class="btn" @click="supervisor(crud.selections)" slot="right" :disabled="crud.selections.some(item=>item.status!==1)">主管审核</el-button>
        <el-button type="primary" size="mini" class="btn" @click="hr(crud.selections)" slot="right" :disabled="crud.selections.some(item=>item.status!==1)">人事审核</el-button>
        <el-button type="primary" size="mini" class="btn" @click="manager(crud.selections)" slot="right" :disabled="crud.selections.some(item=>item.status===4)">经理审核</el-button>
        <el-button type="primary" size="mini" class="btn" @click="reject(crud.selections)" slot="right" :disabled="crud.selections.some(item=>item.status===1)">反审</el-button>
      </crudOperation>
    </div>
    <!-- 表单渲染 -->
    <el-dialog :before-close="crud.cancelCU" :close-on-click-modal="false" :title="crud.status.title"
               :visible.sync="crud.status.cu > 0" append-to-body width="620px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-row :gutter="10">
        <!-- <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="部门"> -->
          <!-- <TreeSelect
            v-model="form.deptId"
            :options="depts"
            placeholder="选择部门"
            style="width:  100%"
            :normalizer="normalizer"
          /> -->
          <!-- <zSelect :value.sync="form.deptId" url="api/dropDown/childSysDeptList" style="width: 100%;"/>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="人员">
          <zSelect :value.sync="form.userId" url="api/dropDown/sysUserList" style="width: 100%;"/>
        </el-form-item>
      </el-col> -->
      <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="加班开始日期" prop="beginTime">
          <el-date-picker
            v-model="form.beginTime"
            type="datetime"
            size="small"
            class="date-item"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss" :picker-options="{
              disabledDate(time) {
                return time.getTime() >= Date.parse(form.endTime)
              },
              selectableRange: endTimeRange
            }"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="加班结束日期" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            size="small"
            class="date-item"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss" :picker-options="{
              disabledDate(time) {
                return time.getTime() <= Date.parse(form.beginTime)- 8.64e7
              },
              selectableRange: startTimeRange
            }"
          />
        </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="业务日期" prop="busDate">
          <el-date-picker
            v-model="form.busDate"
            type="date"
            size="small"
            class="date-item"
            style="width: 100%;"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        </el-col>
        <!-- <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="加班天数" prop="days">
          <el-input v-model="form.days" style="width: 100%;"/>
        </el-form-item>
      </el-col> -->
      <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="加班地点" prop="place">
          <el-input v-model="form.place" style="width: 100%;"/>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="加班内容" prop="content">
          <el-input v-model="form.content" style="width: 100%;"/>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="6">
        <el-form-item label="加班效果" prop="effect">
          <el-input v-model="form.effect" style="width: 100%;"/>
        </el-form-item>
      </el-col>
      </el-row>
        <!-- <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" clearable class="edit-input" placeholder="请选择" style="width: 320px">
                <el-option v-for="(item, index) in dict.dict_process_status" :key="index" :label="item.label" :value="item.value"/>
              </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="submitCU">确认</el-button>
      </div>
    </el-dialog>
    <div class="body-container">
      <!--表格渲染-->
      <el-table ref="table"  border
                height="700"
                show-summary
                v-loading="crud.loading"
                :data="crud.data"
                size="small"
                style="width: 100%;"
                :summary-method="crud.sumRow"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
        <el-table-column :render-header="crud.renderHeader" prop="userName" label="用户名" />
        <el-table-column :render-header="crud.renderHeader" prop="code" label="编码" />
        <el-table-column :render-header="crud.renderHeader" prop="beginTime" label="开始时间" />
        <el-table-column :render-header="crud.renderHeader" prop="endTime" label="结束时间" />
        <el-table-column :render-header="crud.renderHeader" prop="busDate" label="业务日期">
          <template slot-scope="scope">
          {{timestampToTime(scope.row.busDate)}}
        </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" prop="deptName" label="部门名称" />
        <el-table-column :render-header="crud.renderHeader" prop="content" label="加班内容" />
        <el-table-column :render-header="crud.renderHeader" prop="days" label="加班天数" />
        <el-table-column :render-header="crud.renderHeader" prop="place" label="加班地点" />
        <el-table-column :render-header="crud.renderHeader" prop="effect" label="加班效果" />
        <el-table-column :render-header="crud.renderHeader" prop="status" label="状态">
          <template slot-scope="scope">
                    {{ dict.label.dict_process_status[scope.row.status] }}
                  </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
  import workOvertime,{supervisorPass,managerPass,hrPass,reject} from '@/api/erp/workOvertime'
  import CRUD, {crud, form, header, presenter} from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'
  import TreeSelect from '@riophae/vue-treeselect'
  import {getDepts} from "@/api/system/dept";

  // crud交由presenter持有
  const defaultCrud = CRUD({
    title: '加班单', url: '/api/workOvertime/queryAll', sort: 'id,desc', crudMethod: {...workOvertime}, optShow: {
      add: true,
      edit: true,
      del: true,
      download: false,
      leadingIn: false,
      enable: false,
      disable: false,
    },
    props:{
      tableColumns:[
        'name',
        'code'
      ]
    }
  });
  const defaultForm = {
    "beginTime": "",
    "busDate": null,
    "content": "",
    "days": "",
    "deptId": "",
    "effect": "",
    "endTime": "",
    "place": "",
    "userId": "",
  };
  export default {
    name: 'addClasses',
    components: {pagination, crudOperation, rrOperation, udOperation,TreeSelect},
    mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
    dicts: ["dict_process_status"],
    data() {
      return {
        multiple:true,
        permission: {
          //add 不添加权限，这个add按钮自定义
          add: ['admin'],
          edit: ['admin', 'basGoods:edit'],
          del: ['admin', 'basGoods:del'],
          enable: ['admin', 'basGoods:enable'],
          disable: ['admin', 'basGoods:disable'],
        },
        rules: {
          beginTime: {required: true, message: '请选择开始时间', trigger: 'blur'},
          endTime: {required: true, message: '请选择结束时间', trigger: 'blur'}
        },
        depts:[],
        startTimeRange:null,
        endTimeRange:null,
      }
    },
    watch: {
    'form.beginTime': {
      deep:true,
      handler(newValue, oldValue) {
        if (newValue && this.form.endTime) {
            let dt = this.form.endTime.split(' ')
            if (newValue.split(' ')[0] === dt[0]) {
            let st = this.form.endTime.split(' ')[1];
            this.endTimeRange = ['00:00:00 - ' + st];
            } else {
              let st = '23:59:59'
              this.endTimeRange = ['00:00:00 - ' + st];
            }
          
        }else{
            const st = '23:59:59'
            this.endTimeRange = ['00:00:00 - ' + st];
          }
      }
    },
    'form.endTime': {
      deep:true,
      handler(newValue, oldValue) {
        if (newValue && this.form.beginTime) {
            let dt = this.form.beginTime.split(' ')
            if (newValue.split(' ')[0] === dt[0]) {
            let st = this.form.beginTime.split(' ')[1];
            this.startTimeRange = [ st + '- 23:59:59'];
            } else {
              let st = '23:59:59'
              this.startTimeRange = ['00:00:00 - ' + st]
            }
          
        }else{
            const st = '23:59:59'
            this.startTimeRange = ['00:00:00 - ' + st]
          }
      }
    }
  },
    created() {
      this.getdepts()
    },
    methods: {
      submitCU(){
        if (this.form.beginTime===this.form.endTime) {
          this.$message({
              message: '结束时间不能小于等于开始时间',
              type: 'success'
            });
        }else{
          this.crud.submitCU()
        }
      },
      timestampToTime(timestamp) {
        let str = timestamp        //时间戳化成毫秒单位*1000
        let date = new Date(str);        //获取系统时间
        let year = date.getFullYear();
        let month= date.getMonth() + 1;
        month= month< 10 ? ('0' + month) : month;
        let day = date.getDate();
        day = day < 10 ? ('0' + day ) : day ;
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        let m = date.getMinutes();
        m = m < 10 ? ('0' + m) : m;
        let s = date.getSeconds();
        s = s < 10 ? ('0' + s) : s;
        //let w = date.getDay();        //获取星期几
 
    // return year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s;
    return year + '-' + month + '-' + day ;
    },
    supervisor(val){
        const data=val.map(item=>{
        return item.id
        })
        supervisorPass(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      hr(val){
        const data=val.map(item=>{
        return item.id
        })
        hrPass(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      manager(val){
        const data=val.map(item=>{
        return item.id
        })
        managerPass(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      reject(val){
        const data=val.map(item=>{
        return item.id
        })
        reject(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      // getTypeList() {
      //   getTypeList({page: 0, size: 999}).then(res => {
      //     this.typeList = res
      //   })
      // },
      getdepts() {
        getDepts().then(res=>{
        this.depts = res
    })
      },
      normalizer(node) {
        //去掉children=[]的children属性
        if (node.children == null || node.children.length == 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      // 获取数据前设置好接口地址
      [CRUD.HOOK.beforeRefresh]() {
        return true
      }, // 新增与编辑前做的操作
      [CRUD.HOOK.afterToCU](crud, form) {
        if (crud.status.add === CRUD.STATUS.PREPARED) {
          crud.form = JSON.parse(JSON.stringify(defaultForm))
          this.form = crud.form
        }
      },
      //添加提交
      [CRUD.HOOK.afterValidateCU](crud) {
        // if (crud.form.dataScope === '自定义' && crud.form.depts.length === 0) {
        //   this.$message({
        //     message: '自定义数据权限不能为空',
        //     type: 'warning'
        //   })
        //   return false
        // } else if (crud.form.dataScope === '自定义') {
        //   const depts = []
        //   crud.form.depts.forEach(function (data, index) {
        //     const dept = {id: data}
        //     depts.push(dept)
        //   })
        //   crud.form.depts = depts
        // } else {
        //   crud.form.depts = []
        // }
        // return true
      }
    }
  }
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
  .btn{
    display: inline-block;
    vertical-align: middle;
    margin: 0 2px 10px 0;
    margin-left: 5px !important;
  }
</style>
